/**
 * 
 */
package com.google.code.sharebyblog.bravo.currencyconvertor.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.google.code.sharebyblog.bravo.currencyconvertor.domain.CurrencyConversionRequest;
import com.google.code.sharebyblog.bravo.currencyconvertor.domain.CurrencyConversionResponse;


public class CurrenyConversionServiceImpl implements CurrencyConversionService {

	private static final Logger LOGGER = LoggerFactory.getLogger(CurrenyConversionServiceImpl.class);
	private ExchangeRateFinder exchangeRateFinder ;
	
	

	@Override
	public CurrencyConversionResponse process(CurrencyConversionRequest request)
			throws Exception {
		CurrencyConversionResponse response = null;
		
		if(isValid(request)){
			LOGGER.info("Processing : " + request.toString());
			response = new CurrencyConversionResponse();
			response.setCurrencyFrom(request.getCurrencyFrom());
			response.setAmount(request.getAmount());
			Map<String,BigDecimal> convertedAmounts = new HashMap<String,BigDecimal>();
			for(String currency : request.getCurrencyTo()){
				BigDecimal amount = exchangeRateFinder.exchange(request.getCurrencyFrom(), currency, request.getAmount());
				convertedAmounts.put(currency, amount);
				
			}
			Map<String,String> messages = new HashMap<String,String>();
			messages.put("Note", "For developmentpurpose only.");
			response.setMessages(messages);
			response.setCoverted(convertedAmounts);
			
			
		}
		return response;
	}
	
	
	private boolean isValid(CurrencyConversionRequest request){
		boolean isValid = true;
		if(request == null){
			isValid = false;
			return isValid;
		}
		
		if(!StringUtils.hasText(request.getCurrencyFrom()) || 
			request.getAmount() == null || 
			request.getCurrencyTo() == null || 
			request.getCurrencyTo().isEmpty()){
			isValid = false;
		}
		return isValid;
	}


	public ExchangeRateFinder getExchangeRateFinder() {
		return exchangeRateFinder;
	}



	public void setExchangeRateFinder(ExchangeRateFinder exchangeRateFinder) {
		this.exchangeRateFinder = exchangeRateFinder;
	}


	
	
	
	

}
